﻿using OGT.FileTransferClient;
using OGT.FileTransferClient.Service;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DocumentTransferServiceTest
{
    public partial class TransferForm : Form
    {
        public TransferForm()
        {
            InitializeComponent();
        }
        private string _documentTransferServicePath;

        private string _configSavePath = @"E:\新工作\文件服务器\New\配置信息";
        private string _configName = "文档传输测试";
        //文件上传路径
        private string _saveFilePath = @"C:\Users\Administrator\Desktop\FileTransferDatabase";

        private ITransferQueueService _service;
        private List<string> _uploadFiles = new List<string>();
        private DataTable filesTable = new DataTable();

        private void TransferForm_Load(object sender, EventArgs e)
        {
            _documentTransferServicePath = ConfigMgr.GetServer();
            this.textEdit1.Text = _documentTransferServicePath;
            
            InitinalizeTreeList();
        }

        private void TransferForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            ConfigMgr.Save(this.textEdit1.Text);
        }

        /// <summary>
        /// 获取传输服务
        /// </summary>
        /// <param name="configName"> 配置名称，可以任意自定义该名称 </param>
        /// <param name="transferServiceAddress"> 传输服务地址 </param>
        /// <param name="retryTimes"> 重试次数</param>
        /// <param name="retryInterval"> 重试时间（分钟） </param>
        /// <param name="extraInfos"> 扩展信息列 </param>
        /// <param name="allowEncrypt"> 是否加密</param>
        /// <returns> 传输服务</returns>
        public ITransferQueueService InitializeTransferQueueService(string configSavePath, string configName, string transferServiceAddress, int retryTimes, double retryInterval, Dictionary<string, string> extraInfos, bool allowEncrypt)
        {
            //创建传输配置
            TransferQueueConfig tranferConfig = new TransferQueueConfig();
            tranferConfig.Address = transferServiceAddress;
            tranferConfig.AllowEncrypt = allowEncrypt;
            tranferConfig.RetryTimes = retryTimes;
            tranferConfig.RetryInterval = retryInterval;
            //如果不设置SavePath,将默认保存到当前程序目录下
            if (!Directory.Exists(configSavePath))
                Directory.CreateDirectory(configSavePath);
            tranferConfig.SavePath = configSavePath;
            //创建传输管理器      
            if (TransferQueueManager.ServiceCache.ContainsKey(configName) == false)
                TransferQueueManager.RegisterTransferConfig(configName, tranferConfig);

            //创建并初始化传输服务         
            ITransferQueueService service = TransferQueueManager.GetTransferQueueService(configName);
            service.InitializeService();
            return service;
        }

        private void btnConn_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.textEdit1.Text))
                _service = InitializeTransferQueueService(_configSavePath, _configName, this.textEdit1.Text, 10, 0.1, new Dictionary<string, string>() { }, false);
            if (_service != null)
            {
                this.labelControl2.Appearance.ForeColor = Color.LightGreen;
            }
        }

        private void btnUpload_Click(object sender, EventArgs e)
        {
            if (_service == null)
                return;

            OpenFileDialog ofd = new OpenFileDialog();
            ofd.RestoreDirectory = true;
            ofd.ShowDialog();
            UploadFile(ofd.FileName);

        }

        private void InitinalizeTreeList()
        {
            filesTable.Columns.Add("父节点", typeof(string));
            filesTable.Columns.Add("传输队列", typeof(string));
            string[] filePaths = Directory.GetFiles(_saveFilePath);
            for (int i = 0; i < filePaths.Length; i++)
            {
                if (!_uploadFiles.Contains(Path.GetFileName(filePaths[i])))
                {
                    _uploadFiles.Add(Path.GetFileName(filePaths[i]));
                    DataRow row = filesTable.NewRow();
                    row[0] = "null";
                    row[1] = Path.GetFileName(filePaths[i]);
                    filesTable.Rows.Add(row);
                }
            }
            this.treeList1.DataSource = filesTable;
            this.treeList1.ParentFieldName = "父节点";

        }

        private void RefreshTreeList()
        {
            string[] filePaths = Directory.GetFiles(_saveFilePath);
            for (int i = 0; i < filePaths.Length; i++)
            {
                if (!_uploadFiles.Contains(Path.GetFileName(filePaths[i])))
                {
                    _uploadFiles.Add(Path.GetFileName(filePaths[i]));
                    DataRow row = filesTable.NewRow();
                    row[0] = "null";
                    row[1] = Path.GetFileName(filePaths[i]);
                    filesTable.Rows.Add(row);
                }
            }
            this.treeList1.DataSource = filesTable;
            this.treeList1.ParentFieldName = "父节点";
            
        }

        private void UploadFile(string sourceFilePath)
        {
            try
            {
                ////单线程上传,适用于小文件
                //_service.UploadFile(sourceFilePath, null, Path.GetFileName(sourceFilePath));

                //上传一个文件流
                //using (FileStream fsRead = new FileStream(sourceFilePath, FileMode.Open, FileAccess.Read))
                //{
                //    _service.UploadStream(fsRead, null, Path.GetFileName(sourceFilePath));
                //}
                //异步方式上传一个文件
                _service.UploadFileAsync(sourceFilePath, null, Path.GetFileName(sourceFilePath), null);
                _service.UploadCompleted += _service_UploadCompleted;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        void _service_UploadCompleted(object sender, TransferCompletedEventArgs e)
        {
            RefreshTreeList();
        }

        private void btnLookProgress_Click(object sender, EventArgs e)
        {
            if (_service == null)
                return;
            TransferQueueManager.GetTransferManageWindow(_configName).Show();
        }

        private void btnDownload_Click(object sender, EventArgs e)
        {
            try
            {
                if (_service == null)
                    return;
                //同一个进程，保存一个流。
                //DowmloadStream();

                //同一个进程，保存文件。
                // DownloadFile();

                DownloadFileAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void DownloadFileAsync()
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.ShowNewFolderButton = true;
            fbd.Description = "请选择文件保存位置";
            if (fbd.ShowDialog() == DialogResult.OK)
            {
                _service.DownloadFileAsync(null, _uploadFiles[this.treeList1.FocusedNode.Id], fbd.SelectedPath + "\\" + _uploadFiles[this.treeList1.FocusedNode.Id], null);
            }
            _service.DownloadCompleted += _service_DownloadCompleted;
            _service.DownloadException += _service_DownloadException;
        }

        void _service_DownloadException(object sender, TransferExceptionEventArgs e)
        {
            throw new NotImplementedException();
        }

        void _service_DownloadCompleted(object sender, TransferCompletedEventArgs e)
        {
            MessageBox.Show(Path.GetFileName(e.TargetFile)+" 下载成功");
        }

        private void DownloadFile()
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.ShowNewFolderButton = true;
            fbd.Description = "请选择文件保存位置";
            if (fbd.ShowDialog() == DialogResult.OK)
            {
                //参数sourceRelativePath是文件服务器文件保存路径的相对路径。
                _service.DownloadFile(null, _uploadFiles[this.treeList1.FocusedNode.Id], fbd.SelectedPath + "\\" + _uploadFiles[this.treeList1.FocusedNode.Id]);
                MessageBox.Show("OK");
            }
        }

        private void DowmloadStream()
        {
            FolderBrowserDialog BrowDialog = new FolderBrowserDialog();
            BrowDialog.ShowNewFolderButton = true;
            BrowDialog.Description = "请选择文件保存位置";
            if (BrowDialog.ShowDialog() == DialogResult.OK)
            {
                Stream fs = _service.DownloadFile(null, _uploadFiles[this.treeList1.FocusedNode.Id]);

                using (FileStream fsWrite = new FileStream(BrowDialog.SelectedPath + "\\" + _uploadFiles[this.treeList1.FocusedNode.Id], FileMode.Create, FileAccess.Write))
                {
                    byte[] bytes = new byte[1024 * 1024 * 10];
                    int num = fs.Read(bytes, 0, bytes.Length);
                    while (num > 0)
                    {
                        fsWrite.Write(bytes, 0, num);
                        num = fs.Read(bytes, 0, bytes.Length);
                    }
                }
                MessageBox.Show("OK");
            }

        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (_service == null)
                    return;
                DialogResult res = MessageBox.Show("确定要删除选定数据", "警告", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
                if (res == DialogResult.OK)
                {
                    _service.DeleteFile(null, _uploadFiles[this.treeList1.FocusedNode.Id]);
                    _uploadFiles.RemoveAt(this.treeList1.FocusedNode.Id);
                    filesTable.Rows.RemoveAt(this.treeList1.FocusedNode.Id);
                    RefreshTreeList();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
